package webapp.mvc.finders;

import com.google.common.base.Function;
import com.zoowii.jpa_utils.extension.ExtendFinder;
import com.zoowii.jpa_utils.extension.Paginator;
import com.zoowii.jpa_utils.util.ListUtil;
import webapp.mvc.models.ProductCollectEntity;
import webapp.mvc.models.ProductEntity;

import java.util.List;

public class ProductCollectFinder extends ExtendFinder<String, ProductCollectEntity> {
    public ProductCollectFinder(Class<?> kCls, Class<?> mCls) {
        super(kCls, mCls);
    }
    public ProductCollectEntity findByProductAndUser(String productId, String userId) {
        return this.where().eq("productId", productId).eq("userId", userId).first();
    }
    public List<ProductEntity> getCollectedProductsByUser(String userId, Paginator paginator) {
        paginator = paginator.eq("userId", userId);
        List<ProductCollectEntity> productCollectEntities = this.findByPaginator(paginator);
        List<ProductEntity> productEntities = ListUtil.map(productCollectEntities, new Function<ProductCollectEntity, ProductEntity>() {
            @Override
            public ProductEntity apply(ProductCollectEntity productCollectEntity) {
                return ProductEntity.find.byId(productCollectEntity.getProductId());
            }
        });
        productEntities = ListUtil.filter(productEntities, new Function<ProductEntity, Boolean>() {
            @Override
            public Boolean apply(ProductEntity productEntity) {
                return productEntity != null;
            }
        });
        return productEntities;
    }
}
